package com.wavefull.core.ext

import android.app.Activity
import android.content.Context
import android.content.res.Resources
import android.graphics.Color
import android.os.Build
import android.util.TypedValue
import android.view.View
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import com.wavefull.core.DoubleClickListener

fun View.setOnSingleAndDoubleClickListener(onDoubleClickListener: (View, Int) -> Unit) {
    DoubleClickListener.setOnSingleAndDoubleClickListener(this, onDoubleClickListener)
}

fun Int.dp2px(): Int {
    return (this * Resources.getSystem().displayMetrics.density).toInt()
}

fun Int.px2dp(): Int {
    return (this / Resources.getSystem().displayMetrics.density).toInt()
}

/**
 * https://article.juejin.cn/post/7252231214529282085
 * 沉浸式状态栏
 */
fun Activity.fullScreen() {
    WindowCompat.setDecorFitsSystemWindows(window, false)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        //当背景透明时去掉灰色蒙层
        window.isNavigationBarContrastEnforced = false
    }
    //导航栏背景颜色透明
    window.statusBarColor = Color.TRANSPARENT
    window.statusBarColor = Color.TRANSPARENT
    window.navigationBarColor = Color.TRANSPARENT
}

/**
 *
 * WindowInsetsCompat.Type参数解释：
 * WindowInsetsCompat.Type.ime();//键盘
 * WindowInsetsCompat.Type.displayCutout();//刘海屏
 * WindowInsetsCompat.Type.statusBars();//状态栏
 * WindowInsetsCompat.Type.navigationBars();//导航栏
 * WindowInsetsCompat.Type.captionBar();//标题栏
 * WindowInsetsCompat.Type.systemBars();//状态栏,导航栏和标题栏
 * WindowInsetsCompat.Type.systemGestures();//系统手势
 * WindowInsetsCompat.Type.mandatorySystemGestures();//强制性系统手势
 * WindowInsetsCompat.Type.tappableElement();//可点击区域
 */
fun View.getSystemWindow(callback: (Insets) -> Unit) {
    ViewCompat.setOnApplyWindowInsetsListener(this) { view, insets: WindowInsetsCompat ->
        val systemWindow = insets.getInsets(
            WindowInsetsCompat.Type.systemBars() or
                    WindowInsetsCompat.Type.displayCutout()
        )
        callback.invoke(systemWindow)
        insets
    }
}

fun Activity.setLightStatusBars(black: Boolean = true) {
    WindowCompat.getInsetsController(window, window.decorView)?.isAppearanceLightStatusBars = black
}

fun Fragment.setLightStatusBars(black: Boolean = true) {
    requireActivity().setLightStatusBars(black)
}

fun Context.getActionBarSize(defaultDp: Int = 44): Int {
    val actionBarSizeAttributeId = androidx.appcompat.R.attr.actionBarSize
    val typedValue = TypedValue()
    // 获取 actionBarSize 的值
    if (this.theme.resolveAttribute(actionBarSizeAttributeId, typedValue, true)) {
        return TypedValue.complexToDimensionPixelSize(
            typedValue.data,
            this.resources.displayMetrics
        )
    }
    return defaultDp.dp2px()
}

